# coding:utf8

'爬虫路口函数'

from baidu_zhidao import url_manager, html_downloader, html_outputer, html_parser


class SpiderMain(object):
    def __init__(self):
        self.urls = url_manager.UrlManager()
        self.downloader = html_downloader.HtmlDownloader()
        self.parser = html_parser.HtmlParser()
        self.outputer = html_outputer.HtmlOutputer()

    def craw(self, root_url):
        count = 1
        # 将root_url添加进URL管理器
        self.urls.add_new_url(root_url)
        try:
            # 如果url集合中有待爬取得数据,则一直循环
            while self.urls.has_new_url():
                # 从url管理器中取出一条url
                new_url = self.urls.get_new_url()

                print('craw %d : %s' % (count, new_url))

                # 将url放入html下载器进行下载
                html_cont = self.downloader.download(new_url)
                # 将下载的html数据放入parse解析获取新的跳转链接集合和数据
                new_urls, new_data = self.parser.parse(new_url, html_cont)
                # 将新的url继续添加进url管理器
                self.urls.add_new_urls(new_urls)
                # 将数据传给输出器
                self.outputer.collect_data(new_data)

                # 只抓取十天数据
                if count == 10:
                    break
                count = count + 1
        except Exception as e:
            print('craw failed !! ')
            print(e)
        # 将爬取得数据按着需要的格式输出
        self.outputer.output_html()


if __name__ == '__main__':
    root_url = "https://p.baidu.com/daily"
    zd_spider = SpiderMain()
    zd_spider.craw(root_url)
